<script setup lang="ts">
import { Icon } from '@iconify/vue'

type ToastType = 'success' | 'fail' | 'loading'

export interface ToastOptions {
  message: string
  type?: ToastType
  duration?: number
  position?: 'top' | 'middle' | 'bottom'
}

const iconComponent = computed(() => {
  const typeMap = {
    success: 'ic:baseline-check-circle',
    fail: 'ic:baseline-cancel',
    loading: 'svgis-spinners:90-ring-with-bg',
  }
  return typeMap[options.value.type as keyof typeof typeMap]
})

const visible = ref(false)
const options = ref<ToastOptions>({ message: '' })

const show = (opt: string | ToastOptions) => {
  visible.value = true
  options.value = typeof opt === 'string' ? { message: opt } : opt

  if (options.value.type !== 'loading') {
    setTimeout(hide, options.value.duration || 2000)
  }
}

const hide = () => {
  visible.value = false
}

defineExpose({ show, hide })
</script>

<template>
  <teleport to="body">
    <transition name="van-fade">
      <div
        v-show="visible"
        class="van-toast"
        :class="[options.position || 'middle']"
      >
        <Icon :icon="iconComponent" class="text-xl" />
        <span class="van-toast__text">{{ options.message }}</span>
      </div>
    </transition>
  </teleport>
</template>
<style scoped lang="scss">
@use './Toast.scss';
</style>
